<?php

namespace yphp;

class Tap extends Instance
{
    # 路由
    protected $url;
    # 方式数组
    protected $method;
    // 路由正则数组
    protected $where = [];
    // POST数组
    protected $input = [];

    function construct($method, $url)
    {
        $this->method = $method;
        $this->url = $url;
    }

    // 路由参数
    function where($key, $rule = null)
    {
        $where = is_array($key) ? $key : [$key => $rule];
        foreach ($where as $key => $preg) {
            $this->where[$key] = $preg;
        }
        foreach ($this->method as $method) {
            if ($method === 'POST') throw new \Exception('post请求不支持where参数');
            Route::$RouteArr[$method][$this->url]['where'] = $this->where;
        }
        return $this;
    }

    // post参数
    function input($key, $rule = null, $msg = null)
    {
        if (in_array('POST', $this->method)) {
            $input = is_array($key) ? $key : (is_null($msg) ? [$key => $rule] : [$key => [$rule, $msg]]);
            foreach ($input as $key => $preg) {
                $this->input[$key] = $preg;
            }
            Route::$RouteArr['POST'][$this->url]['input'] = $this->input;
        }
        return $this;
    }

    // 路由缓存
    function cache($time)
    {
        foreach ($this->method as $method) {
            Route::$RouteArr[$method][$this->url]['cache'] = $time;
        }
        return $this;
    }

    // 解析路由参数
    function parse()
    {
        $path = str_replace('/', '\\/', $this->url);
        foreach ($this->where as $key => $preg) {
            $path = str_replace(['{' . $key . '}', '@{' . $key . '?}'], ['(' . $preg . ')', '(@' . $preg . ')?'], $path);
        }
        foreach ($this->method as $method) {
            Route::$RouteArr[$method][$this->url]['preg'] = $path;
        }
        return $this;
    }


}